import 'package:flutter/cupertino.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'package:love_app/common/su.dart';
import 'package:love_app/common/su_dialog.dart';
import 'package:love_app/config/setting.dart';
import 'package:love_app/db/socket_db.dart';
import 'package:love_app/enum/notification_title.dart';
import 'package:love_app/enum/socket.dart';
import 'package:love_app/init/notifications_init.dart';
import 'package:love_app/model/chat_sql_model.dart';
import 'package:love_app/model/socket_model.dart' as SKModel;
import 'package:love_app/providers/chat_log_provider.dart';
import 'package:love_app/providers/socket_object_provider.dart';
import 'package:provider/provider.dart';
import 'package:web_socket_channel/io.dart';
import 'dart:convert';

import '../main.dart';

// 全局socket初始化
class SocketInit {
  static void socketInit(BuildContext context, String toekn, int uid) {
    final SocketObjetProvider socketObjetProvider =
        Provider.of<SocketObjetProvider>(context, listen: false);
    final ChatLogProvider chatLogProvider =
        Provider.of<ChatLogProvider>(context, listen: false);
    try {
      String socketUrl = Setting.SocketUrl;
      IOWebSocketChannel channel = IOWebSocketChannel.connect(socketUrl,
          pingInterval: Duration(seconds: 5));
      // 初始化需要握手socket数据
      Map<String, dynamic> headers = {
        "class": SocketClassToString.getClass(SocketClass.classIndex),
        "action": SocketAccionToString.getAcction(SocketAccion.actionIndex),
        "content": {
          "xAuthToken": toekn,
          "clientType": 1,
          "fd": "0",
          "addTime": 0,
        }
      };
      channel.sink.add(jsonEncode(headers)); // 建立长连接(socket)
      socketObjetProvider.channel = channel;
      // 直接用全局的channel
      socketObjetProvider.channel.stream.listen(
        (data) {
          Su.suPrints(data);
          Map<String, dynamic> mapData = json.decode(data);
          if(mapData['code'] == 200){
            // 监听stream
          _sendSql(mapData, socketObjetProvider, uid, chatLogProvider);
          }
        },
        onError: (error) {
          Su.suPrints("悄悄话初始化失败，进入onError");
          SuDialog.showToast("悄悄话初始化失败，进入onError");
        },
        onDone: () {
          SuDialog.showToast("socket连接失效");
          Su.suPrints("socket连接失效");
        },
        cancelOnError: false,
      );
      // socketObjetProvider.channel = channel;
    } catch (error) {
      SuDialog.showToast("悄悄话初始化失败，进入catch");
    }
  }

  // 把消息写入到数据库
  static _sendSql(Map<String, dynamic> mapData, SocketObjetProvider socketObjetProvider, int uid,
      ChatLogProvider chatLogProvider) {
    SKModel.SocketModel socketModel = SKModel.SocketModel.fromJson(mapData);
    List<SKModel.Lists> lists = socketModel.data.lists;
    socketObjetProvider.fd = socketModel.data.fd;
    // Su.suPrints(lists.toString());
    if (lists.length > 0) {
      // 把接收到的聊天记录保存到数据库
      lists.forEach((item) async {
        // 写入数据库的只有别的聊天记录， 自己的聊天记录不写入
        if (item.sendUid != uid) {
          int id = await SocketDb().insertHasJudgment(item);
          _showNotification(NotificationType.message, item.text);
          Map<String, dynamic> map = {
            "id": id,
            "logId": -1,
            "sendUid": item.sendUid,
            "content": item.text,
            "type": item.type,
            "addTime": DateTime.now().millisecondsSinceEpoch,
          };
          ChatSqlModel chatSqlModel = ChatSqlModel.fromJson(map);
          chatLogProvider.addLogInFirst(chatSqlModel);
        }
        chatLogProvider.notify();
      });
    }
  }

  /// 消息推送到状态栏
  static Future<void> _showNotification(NotificationType type, String message) async {
    String title = NotificationToString.to(type);
    //安卓的通知配置，必填参数是渠道id, 名称, 和描述, 可选填通知的图标，重要度等等。
    var androidPlatformChannelSpecifics = new AndroidNotificationDetails(
        '201', 'lqb', '有新的消息',
        importance: Importance.Max, priority: Priority.High);
    //IOS的通知配置
    var iOSPlatformChannelSpecifics = new IOSNotificationDetails();
    var platformChannelSpecifics = new NotificationDetails(
        androidPlatformChannelSpecifics, iOSPlatformChannelSpecifics);
    //显示通知，其中 0 代表通知的 id，用于区分通知。
    await flutterLocalNotificationsPlugin.show(
        2010, title, message, platformChannelSpecifics,
        payload: 'message');
  }
}
